from flask import Blueprint, jsonify
from flask import Blueprint, request, render_template, redirect
from .models import *
from functools import wraps
import time

"""
此文件用于存放路由和视图函数
"""

blue = Blueprint('user', __name__)

admin = Blueprint('admin', __name__)


# 登录装饰器
def login_check(fn):
    @wraps(fn)
    def inner(*args, **kwargs):
        user_id = request.cookies.get('user_id', None)
        if user_id:
            user = User.query.get(user_id)
            request.user = user
            return fn(*args, **kwargs)
        else:
            return redirect('/login/')

    return inner


# 管理员后台
@admin.route('/admin/', methods=['GET', 'POST'])
@login_check
def _admin():
    if request.method == 'GET':
        user = request.user
        goodss = Goods.query.filter_by(user_id=user.id)
        return render_template('admin.html', user=user, goodss=goodss)
    elif request.method == 'POST':
        return 'ok'


# 注册
@admin.route('/signin/', methods=['GET', 'POST'])
def admin_signin():
    if request.method == 'GET':
        return render_template('signin.html')
    elif request.method == 'POST':
        # 获取前端提交的注册信息
        username = request.form.get('username')
        userpwd = request.form.get('userpwd')
        name = request.form.get('name')
        id_card = request.form.get('id_card')
        email = request.form.get('email')
        mobile_num = request.form.get('mobile_num')
        # 将注册信息插入到数据库
        user = User()
        user.username = username
        user.password = userpwd
        user.name = name
        user.id_card = id_card
        user.email = email
        user.mobile_num = mobile_num

        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            print(e)
            db.session.rollback()
            return render_template('signin.html', msg='注册失败，请检查数据')
        return render_template('signin.html', msg='注册成功')


# 登录
@admin.route('/login/', methods=['GET', 'POST'])
def admin_login():
    if request.method == 'GET':
        return render_template('login.html')
    elif request.method == 'POST':
        username = request.form.get('username')
        userpwd = request.form.get('userpwd')
        user = User.query.filter_by(username=username,
                                    password=userpwd).first()  # 将获取到的账号密码与数据库中账号密码对比，有则返回True，默认返回False
        if user:
            # 登陆成功
            response = redirect('/index/')  # 跳转到首页
            response.set_cookie('user_id', str(user.id), max_age=24 * 3600)  # 将id设置为cookie，过期时间为1天
            return response
        else:
            # 登陆失败
            return render_template('login.html', msg='用户名或密码错误！')


# 注销登录
@blue.route('/logout/')
@login_check
def logout():
    response = redirect('/login/')
    response.delete_cookie('user_id')
    return response


# 首页
@blue.route('/')
@blue.route('/index/')
@login_check
def index():
    user = request.user

    return render_template('index.html', user=user)


# 买商品
@blue.route('/sp/')
@login_check
def sp():
    user = request.user
    page = int(request.args.get('page', 1))
    per_page = int(request.args.get('per_page', 10))
    goods = Goods.query.paginate(page=page, per_page=per_page, error_out=False)
    # goods = Goods.query.all()goods=goods
    return render_template('sp.html',
                           user=user,
                           goods=goods
                           )


# 卖商品
@blue.route('/sell/', methods=['GET', 'POST'])
@login_check
def sell():
    user = request.user
    if request.method == 'GET':
        return render_template('sell.html', user=user)

    elif request.method == 'POST':
        g_name = request.form.get('g_name')  # 商品名称
        describe = request.form.get('describe')  # 商品描述
        g_type = request.form.get('g_type')  # 商品类型
        price = request.form.get('price')  # 商品价格
        img = request.files.get('img')  # 图片

        img_name = f'{time.time()}-{img.filename}'
        img_url = f'flask/App/static/imgs/upimgs/{img_name}'
        img_db_url = f'../static/imgs/upimgs/{img_name}'

        try:
            goods = Goods()

            goods.g_name = g_name
            goods.describe = describe
            goods.g_type = g_type
            goods.price = price
            goods.img = img_db_url
            goods.user_id = user.id

            db.session.add(goods)
            db.session.commit()
        except Exception as e:
            db.session.rollback()
            db.session.flush()
            print(e)
        else:
            img_data = img.read()
            with open(img_url, 'wb') as fp:
                fp.write(img_data)
                fp.flush()

        return render_template('sell.html', user=user)


@blue.route('/del/', methods=['GET', 'POST'])
@login_check
def dle_sp():
    user = request.user
    if request.method == 'POST':
        g_id = request.form.get('g_id')
        goods = Goods.query.get(g_id)
        try:
            db.session.delete(goods)
            db.session.commit()
        except Exception as e:
            print('e', e)
            return jsonify({'code': 500, 'msg': '删除失败！'})
        return jsonify({'code': 200, 'msg': '删除成功！'})
    return jsonify({'code': 400, 'msg': '请求错误！'})


@admin.route('/buyAdmin/', methods=['GET', 'POST'])
@login_check
def buyAdmin():
    user = request.user
    orders = Order.query.filter_by(user_id=user.id)

    return render_template('buy.html', user=user, orders=orders)


@blue.route('/buy/', methods=['GET', 'POST'])
@login_check
def buy():
    user = request.user

    if request.method == 'POST':
        g_id = request.form.get('g_id')
        goods = Goods.query.get(g_id)
        print(user.balance)
        print(goods.price)
        if user.balance >= goods.price:
            try:
                user.balance = user.balance - goods.price
                orders = Order()
                orders.g_name = goods.g_name
                orders.describe = goods.describe
                orders.g_type = goods.g_type
                orders.price = goods.price
                orders.img = goods.img
                orders.user_id = goods.user_id

                db.session.add(orders)
                db.session.delete(goods)
                db.session.commit()
            except Exception as e:
                print('e', e)
                return jsonify({'code': 500, 'msg': '购买失败！'})
            return jsonify({'code': 200, 'msg': '购买成功！'})
        else:
            return jsonify({'code': 500, 'msg': '您的余额不足，请联系管理员充值！'})


@blue.route('/echarts/', methods=['GET', 'POST'])
@login_check
def echarts():
    return render_template('echarts.html')
